<template>
  <div class="favorites-container">
    <div class="favorites-header">
      <h1>我的收藏</h1>
      <div class="favorites-actions">
        <el-button type="primary" @click="refreshFavorites">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-card class="favorites-content" v-loading="loading">
      <template v-if="!loading && favorites.length === 0">
        <el-empty description="暂无收藏课程">
          <el-button type="primary" @click="$router.push('/courses')">浏览课程</el-button>
        </el-empty>
      </template>

      <div v-else class="favorites-grid">
        <div v-for="item in favorites" :key="item.id" class="favorite-item">
          <CourseCard 
            :course="item.course" 
            :already-favorited="true"
            @favorite-changed="handleFavoriteChange"
          />
        </div>
      </div>

      <div class="pagination" v-if="total > 0">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @update:current-page="currentPage = $event"
          @update:page-size="pageSize = $event"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import request from '@/utils/request'
import CourseCard from '@/components/frontend/CourseCard.vue'

const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const favorites = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

onMounted(() => {
  if (userStore.isLoggedIn) {
    fetchUserFavorites()
  } else {
    ElMessage.warning('请先登录后查看收藏')
    router.push('/login')
  }
})

// 获取用户收藏列表
const fetchUserFavorites = async () => {
  loading.value = true
  
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    await request.get(`/favorite/user/${userStore.userInfo.id}`, params, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        favorites.value = data.records||[]
        total.value = data.total||0
      },
      onError: (error) => {
        console.error('获取收藏列表失败:', error)
        ElMessage.error('获取收藏列表失败')
      }
    })
  } catch (error) {
    console.error('获取收藏列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchUserFavorites()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchUserFavorites()
}

// 处理收藏状态变化
const handleFavoriteChange = ({ courseId, favorited }) => {
  if (!favorited) {
    // 如果取消了收藏，从列表中移除
    favorites.value = favorites.value.filter(item => item.courseId !== courseId)
    total.value--
    
    // 如果当前页无内容但总数不为0，回到上一页
    if (favorites.value.length === 0 && total.value > 0 && currentPage.value > 1) {
      currentPage.value--
      fetchUserFavorites()
    }
  }
}

// 刷新收藏列表
const refreshFavorites = () => {
  fetchUserFavorites()
}
</script>

<style scoped>
.favorites-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.favorites-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.favorites-header h1 {
  margin: 0;
  font-size: 24px;
  color: var(--el-color-primary);
}

.favorites-content {
  min-height: 400px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.favorite-item {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }
  
  .favorites-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style> 